package gw.com.android.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;

import com.flyco.tablayout.SlidingTabLayout;

import www.com.library.util.DeviceUtil;

/**
 * @author jett
 * @since 2018-12-05.
 */
public class SpaceTabLayout extends SlidingTabLayout {

    public SpaceTabLayout(Context context) {
        super(context);
        init();
    }

    public SpaceTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public SpaceTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setTabSpaceEqual(false);
        setTabPadding(0);

        /*Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(getTextsize());
        float textWidth = mTextPaint.measureText("自选外汇商品数字货币指数参考");
        int screenWidth = DeviceUtil.instance().getScreenPixelsWidth(getContext());
        float tabPadding = (screenWidth - textWidth) * 1.0F / 13;
        setTabPadding(px2dip(tabPadding));
        setPadding((int) (tabPadding / 2), 0, (int) (tabPadding / 2), 0);*/

        final ViewGroup child = (ViewGroup) getChildAt(0);
        child.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int width = 0;
                int count = child.getChildCount();
                if (count <= 0) {
                    return;
                }
                for (int i = 0; i < count; i++) {
                    View view = child.getChildAt(i);
                    if (view == null) {
                        return;
                    }
                    width += view.getWidth();
                }
                int screenWidth = DeviceUtil.instance().getScreenPixelsWidth(getContext());
                float tabPadding = (screenWidth - width) * 1.0F / (count * 2 + 1) - 1;
                setTabPadding(px2dip(tabPadding));
                setPadding((int) (tabPadding / 2), 0, 0, 0);
                child.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });
    }

    public float px2dip(float pxValue) {
        return pxValue / getContext().getResources().getDisplayMetrics().density;
    }

}
